/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package database.databasemanager;

import java.sql.*;
import database.databasemanager.configuration.DataBaseAccessInfoLabels;
import database.databasemanager.configuration.DataBaseInfoLoader;
import database.databasemanager.exceptions.ConnectionFailureException;
import database.databasemanager.exceptions.ConnectionNotFoundException;
import database.databasemanager.exceptions.DataBaseException;
import database.databasemanager.exceptions.InvalidDriverException;
import database.databasemanager.exceptions.InvalidStatementException;

/**
 *
 * @author Vicky
 */
public class DataBaseManager {
    
    private DataBaseInfoLoader infoLoader;
    private Connection connection;

public void openConnection() throws DataBaseException {
        try {
            infoLoader.loadDataBaseAccessInfo();
            Class.forName(DataBaseAccessInfoLabels.MYSQL_DRIVER);
            connection = DriverManager.getConnection(infoLoader.getDataBaseAddress(),
                                                     infoLoader.getDataBaseUserName(),
                                                     infoLoader.getDataBaseUserPassword());
        }catch (ClassNotFoundException exception) {
            throw new InvalidDriverException(exception);
        }catch (SQLException exception) {
            throw new ConnectionFailureException(exception);
        }

}

public ResultSet executeQuery(String sqlSentence) throws DataBaseException{
        try {
            Statement sqlStatementExecuter=connection.createStatement();
            ResultSet tabla = sqlStatementExecuter.executeQuery(sqlSentence);
            return tabla;
        }catch(NullPointerException exception){
            throw new ConnectionNotFoundException(exception);
        }catch (SQLException exception) {
            throw new  InvalidStatementException(exception);
        }
}

public void executeUpdate(String sqlSentence) throws DataBaseException{
        try {
                Statement sqlStatementExecuter=connection.createStatement();
                sqlStatementExecuter.executeUpdate(sqlSentence);
            }catch(NullPointerException exception){
               throw new ConnectionNotFoundException(exception);
            } catch (SQLException exception) {
               throw new  InvalidStatementException(exception);
            }
}


public void closeConnection() throws DataBaseException{
        try {
            if (!connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException exception) {
            throw new ConnectionNotFoundException(exception);
        }
}

}
